<template>
	<view>
		<uni-notice-bar show-icon scrollable :speed="50" :text="notice" />
		<view class="register-view">
			<uni-forms ref="registerFormRef" :model="registerFormData" :label-width="85" :rules="rules">
				<uni-forms-item label="头像" name="avatar" required>
					<button class="avatar" type="default" size="mini" open-type="chooseAvatar"
						@chooseavatar="chooseavatar">
						<image :src="avatar"></image>
					</button>
				</uni-forms-item>
				<uni-forms-item label="昵称" name="nickname" required>
					<uni-easyinput type="text" v-model="registerFormData.nickname" placeholder="昵称" />
				</uni-forms-item>
				<uni-forms-item label="用户名" name="username" required>
					<uni-easyinput type="text" v-model="registerFormData.username" placeholder="用户名" />
				</uni-forms-item>
				<uni-forms-item label="密码" name="password" required>
					<uni-easyinput type="password" v-model="registerFormData.password" placeholder="6-20位密码" />
				</uni-forms-item>
				<uni-forms-item label="确认密码" name="confirmpassword" required>
					<uni-easyinput type="password" v-model="registerFormData.confirmpassword" placeholder="确认密码" />
				</uni-forms-item>
				<uni-forms-item label="性别" name="sex" required>
					<uni-data-checkbox v-model="registerFormData.sex" :localdata="sexes" />
				</uni-forms-item>
				<uni-forms-item label="手机号码" name="telephone" required>
					<uni-easyinput type="mobile" v-model="registerFormData.telephone" placeholder="请输入中国大陆手机号" />
				</uni-forms-item>
				<uni-forms-item label="验证码" name="captcha" required>
					<view class="captcha-view">
						<view style="width: 50%;">
							<uni-easyinput type="text" v-model="registerFormData.captcha" placeholder="验证码" />
						</view>
						<view style="width: 48%;">
							<button type="default" style="width: 98%;height: 35px;" size="mini" :disabled="isCountdown"
								@tap="getCaptcha">
								<text v-if="!isCountdown">获取验证码</text>
								<text v-else>{{ttl}}s后重发</text>
							</button>
						</view>
					</view>

				</uni-forms-item>
			</uni-forms>
			<button type="primary" @tap="register">注册</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		watch
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import baseApi from '@/api/base.js'
	import userApi from '@/api/user.js'
	import {
		error
	} from 'console';
import { rejects } from 'assert';

	const sexes = ref([]);
	// 发起请求
	onLoad( async () => {
		let res = await baseApi.getParamListByBaseName('sex')
		sexes.value = res.data.map(item => {
			return {
				text: item.paramName,
				value: item.paramValue
			}
		});
	})

	const registerFormRef = ref()
	const registerFormData = ref({})
	const register = () => {
		registerFormRef.value.validate().then(res => {
			registerFormData.value.type = '1';
			userApi.register(registerFormData.value).then(regRes => {
				uni.showToast({
					icon:'success',
					title:'注册成功'
				})
				uni.navigateTo({
					url: '/pages/register/success'
				})
			});
			
		}).catch(err => {
			console.log('验证失败：', err);
		})
	}

	// 头像
	import fileApi from '@/api/file.js'
	const avatar = ref("/static/icon/avatar.png")
	const chooseavatar = (e) => {
		console.log("chooseavatar: ", e)
		
		fileApi.uploadFile(e.detail.avatarUrl).then(res => {
			avatar.value = e.detail.avatarUrl;
			registerFormData.value.avatar = res.data.fileName;
			console.log(registerFormData.value);
		})
		
		
	}

	// 验证码
	const isCountdown = ref(false)
	const ttl = ref(30);
	let timer = '';
	const getCaptcha = () => {
		if(registerFormData.value.telephone == null)
		{
			uni.showToast({
				icon:'error',
				title:"请先输入手机号码"
			})
			return false;
		}
		userApi.sendSms(registerFormData.value.telephone).then(res => {
			isCountdown.value = true;
			timer = setInterval(() => {
				ttl.value--
			}, 1000)
		})
		
	}

	watch(ttl, (value) => {
		if (value <= 0) {
			clearInterval(timer);
			isCountdown.value = false;
			ttl.value = 10;
		}
	})


	const notice = ref("注册即可获得咖啡豆8折优惠券！")

	// 验证规格
	const rules = {
		nickname: {
			rules: [
				// 校验 nickname 不能为空
				{
					required: true,
					errorMessage: '请输入昵称',
				},
				{
					minLength: 2,
					errorMessage: '用户名长度最少 {minLength} 个字符',
				},
			]
		},
		username: {
			rules: [
				// 校验 username 不能为空
				{
					required: true,
					errorMessage: '请输入用户名',
				},
				{
					minLength: 3,
					errorMessage: '用户名长度最少 {minLength} 个字符',
				},
				{
					validateFunction: (rule, value, data, callback) => {
						// 异步需要返回 Promise 对象
						return new Promise((resolve, reject) => {
							userApi.checkUserName(value).then(res => {
								console.log('check username request:....: ', res);
								if (res.data > 0) {
									reject(new Error('用户名已存在'))
								}
								resolve()
							})
						})
					}
				}
			]
		},
		password: {
			rules: [
				// 校验 password 不能为空
				{
					required: true,
					errorMessage: '请输入密码',
				},
				{
					minLength: 6,
					errorMessage: '密码长度最少 {minLength} 个字符',
				},
			]
		},
		confirmpassword: {
			rules: [
				// 校验 confirmpassword 不能为空
				{
					required: true,
					errorMessage: '请再次输入密码',
				},
				{
					minLength: 6,
					errorMessage: '密码长度最少 {minLength} 个字符',
				}, {
					validateFunction: function(rule, value, data, callback) {
						if (value != data.password) {
							callback('两次密码输入不一致')
						}
						return true
					}
				}
			]
		},
		sex: {
			rules: [
				// 校验 sex 不能为空
				{
					required: true,
					errorMessage: '请选择性别',
				}
			]
		},
		telephone: {
			rules: [
				// 校验 telephone 不能为空
				{
					required: true,
					errorMessage: '请输入手机号',
				},
				{
					minLength: 11,
					errorMessage: '手机号长度最少 {minLength} 个字符',
				},
				{
					validateFunction: function(rule, value, data, callback) {
						let regex = /^1[3-9]\d{9}$/;
						if (!regex.test(value)) {
							callback('手机格式不正确')
						}
						return true
					}
				}
			]
		},
		captcha: {
			rules: [
				// 校验 验证码 不能为空
				{
					required: true,
					errorMessage: '请输入验证码',
				},
				{
					validateFunction: (rule, value, data, callback) => {
						// 异步需要返回 Promise 对象
						return new Promise((resolve, reject) => {
							
							userApi.validCaptcha(data.telephone, value).then(res => {
								if (!res.data) {
									reject(new Error('验证码错误'))
								}
								resolve()
							});
						})
					}
				}
			]
		},
	};
</script>

<style lang="scss">
	.register-view {
		padding: 20px;

		.avatar {
			width: 56px;
			height: 56px;
			padding: 0;
			background-color: gray;
			box-shadow: 0 0 5px gray;

			image {
				width: 56px;
				height: 56px;
			}
		}
	}

	.captcha-view {
		display: flex;
		justify-content: space-between;

	}
</style>